//
//  JXLoginViewController.m
//

#import "JXLoginViewController.h"

#import "JXLandTextField.h"
#import "JXMCSUserManager.h"
#import "QRCodeReaderViewController.h"

#define kBorderColor JXPureAlphaColor(204.0, 1.0)
#define kOpenLoginBtnTag 2000
#define kBackGroundColor JXPureAlphaColor(249, 1.0)

#define kTableHeaderDefaultColor JXPureAlphaColor(246.0)
#define kUnActiveBorderColor JXPureAlphaColor(204.0, 1.0)
#define kActiveBorderColor JXColorWithRGB(104.0, 192.0, 46.0)

#define kCustomSpaceX 10
#define kNavBarHeight 64
#define kCustomHeight 44

@interface JXLoginViewController ()<JXLandTextFieldDelegate, JXClientDelegate, QRCodeReaderDelegate>

@property(nonatomic, strong) JXLandTextField *appKeyTextField;
@property(nonatomic, strong) UIButton *loginBtn;
@property(nonatomic, strong) UIButton *scanBtn;

@end

@implementation JXLoginViewController

#pragma mark -
#pragma mark - controller life circle

- (void)dealloc {
    _appKeyTextField.delegate = nil;
}

- (void)loadView {
    [super loadView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBackGroundColor;
    [self setTitle:@"登录"];
    _appKeyTextField =
            [[JXLandTextField alloc] initWithFrame:CGRectZero HeadType:JXTextFieldHeadTypeText];
    [_appKeyTextField setTextFiledHeadTitle:@"账号" Color:JXPureAlphaColor(102.0, 1.0)];
    _appKeyTextField.placeholder = @"开发者AppKey";
    _appKeyTextField.textFontSize = 14;
    _appKeyTextField.headFontSize = 15;
    _appKeyTextField.unActiveBorderColor = kUnActiveBorderColor;
    _appKeyTextField.activeBorderColor = kActiveBorderColor;
    _appKeyTextField.textField.returnKeyType = UIReturnKeyNext;
    _appKeyTextField.textField.textColor = [UIColor grayColor];
    _appKeyTextField.delegate = self;
    [self.view addSubview:_appKeyTextField];

    NSString *cachedAppKey = [[NSUserDefaults standardUserDefaults] objectForKey:kJXCachedAppKey];
    if (cachedAppKey) {
        _appKeyTextField.text = cachedAppKey;
    }
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.layer.masksToBounds = YES;
    _loginBtn.layer.cornerRadius = 4.0;
    [_loginBtn setBackgroundColor:JXColorWithRGB(255, 134, 107)];
    _loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginBtn addTarget:self
                      action:@selector(loginUser)
            forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];

    UITapGestureRecognizer *tapGestureRecognizer =
            [[UITapGestureRecognizer alloc] initWithTarget:self
                                                    action:@selector(resignFirstInputResponder)];
    [self.view addGestureRecognizer:tapGestureRecognizer];

    _scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _scanBtn.layer.masksToBounds = YES;
    _scanBtn.layer.cornerRadius = 4.0;
    [_scanBtn setBackgroundColor:JXColorWithRGB(255, 134, 107)];
    _scanBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [_scanBtn setTitle:@"扫描二维码" forState:UIControlStateNormal];
    [_scanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_scanBtn addTarget:self
                      action:@selector(skipToQRVC)
            forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_scanBtn];

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *appV = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *appVersion = [NSString stringWithFormat:@"v%@", appV];
    // app build版本
    // NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    UILabel *versionLabel = [[UILabel alloc]
            initWithFrame:CGRectMake((selfViewWidth - 120) / 2,
                                     (selfViewHeight - sNavBarHeight - 60), 120, 30)];
    versionLabel.textAlignment = NSTextAlignmentCenter;
    versionLabel.textColor = [UIColor grayColor];
    versionLabel.text = appVersion;
    [self.view addSubview:versionLabel];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    _appKeyTextField.frame = CGRectMake(kCustomSpaceX, kNavBarHeight + 55,
                                        self.view.width - 2 * kCustomSpaceX, kCustomHeight);
    _loginBtn.frame =
            CGRectMake(kCustomSpaceX, _appKeyTextField.bottom + 60, _appKeyTextField.width, 42);
    _scanBtn.frame = CGRectMake(kCustomSpaceX, _loginBtn.bottom + 15, _appKeyTextField.width, 42);
    CGFloat width = 64;
    CGFloat space = 20;
    for (UIView *subview in [self.view subviews]) {
        if (subview.tag >= kOpenLoginBtnTag) {
            NSInteger index = subview.tag - kOpenLoginBtnTag;
            subview.frame = CGRectMake(kCustomSpaceX + index * (space + width),
                                       _loginBtn.bottom + 30, width, width);
            subview.layer.cornerRadius = width / 2;
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:JXImage(@"basicNav")
                                                  forBarMetrics:UIBarMetricsDefault];
}

- (void)resignFirstInputResponder {
    [self.appKeyTextField resignFirstInputResponder];
}

#pragma mark -
#pragma mark -  JXLandTextFieldDelegate
- (void)textFieldDidBeginEditing:(JXLandTextField *)textField {
}

- (void)textFiledFinisedEdit:(JXLandTextField *)textField {
    [self.appKeyTextField resignFirstInputResponder];
}

- (void)textFieldReturnBtnTouched:(JXLandTextField *)textField {
    [self.appKeyTextField resignFirstInputResponder];
}

#pragma mark -
#pragma mark -  Private method

- (BOOL)loginMessageIsLegal {
    if (self.appKeyTextField.textField.text.length <= 0) {
        [sJXHUD showMessage:@"请输入账号" duration:0.8];
        return NO;
    }
    return YES;
}

- (void)skipToQRVC {
    static QRCodeReaderViewController *reader = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        reader = [QRCodeReaderViewController new];
        reader.modalPresentationStyle = UIModalPresentationPageSheet;
    });
    reader.delegate = self;
    [reader setCompletionWithBlock:^(NSString *resultAsString) {
        if (resultAsString.length == 0) {
            return;
        }
        NSData *decodedData = [[NSData alloc]
                initWithBase64EncodedString:resultAsString
                                    options:NSDataBase64DecodingIgnoreUnknownCharacters];
        NSString *decodedString =
                [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
        NSDictionary *resultDic = [decodedString objectFromJsonString];
        NSString *appKey = [resultDic objectForKey:@"appKey"];
        if (appKey) {
            _appKeyTextField.text = appKey;
        }
    }];

    [self presentViewController:reader animated:YES completion:NULL];
}

#pragma mark -
#pragma mark - UI response method

- (void)loginUser {
    [self.appKeyTextField resignFirstInputResponder];
    if ([self loginMessageIsLegal]) {
        //__weak typeof(self) weakSelf = self;
        [sJXHUD showMessageWithActivityIndicatorView:@"正在登录..."];
        [[JXMCSUserManager sharedInstance]
                loginWithAppKey:self.appKeyTextField.text
                 responseObject:^(BOOL success, id responseObject) {
                     if (success) {
                         [self loginSuccessed];
                     } else {
                         dispatch_after(
                                 dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.f * NSEC_PER_SEC)),
                                 dispatch_get_main_queue(), ^{
                                     JXError *error = responseObject;
                                     [sJXHUD showMessage:[error getLocalDescription] duration:1.f];
                                 });
                     }
                 }];
    }
}

- (void)loginSuccessed {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.f * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
                       [sJXHUD hideHUD];
                       AppDelegate *currentDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                       [UIView animateWithDuration:0.4
                               animations:^{
                                   currentDelegate.loginWindow.frame =
                                           CGRectMake(0, JXScreenSize.height, JXScreenSize.width,
                                                      JXScreenSize.height);
                               }
                               completion:^(BOOL finished) {
                                   currentDelegate.loginWindow.hidden = YES;
                                   [currentDelegate.loginWindow resignKeyWindow];
                                   currentDelegate.loginWindow = nil;
                               }];
                   });
}

#pragma mark - QRCodeReader Delegate Methods

- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result {
    [self dismissViewControllerAnimated:YES
                               completion:^{
                                   //是否需要自动去登录
                                   [self loginUser];
                               }];
}

- (void)readerDidCancel:(QRCodeReaderViewController *)reader {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

@end
